/* eslint-disable no-shadow */
/* eslint-disable no-debugger */
/**
 * 查询页面组件
 * @description
 * 根据入参生成在查询页面组件；
 * 1、查询页面内容包括：
 *    1）查询条件Form;
 *    2）查询结果列表；
 * 2、查询页面包括功能：
 *    1）查询条件Form本身所带功能；
 *    2）点击按钮“查询”调用查询API功能；
 *    3）查询结果列表FCTable本身所具备功能；
 *    4）查询结果列表翻页功能。
 * @author LiAnqi
 * @Date 2022-03-01
 *
 */

import React, {
  useMemo,
  useState,
  useEffect,
  useRef,
  useCallback,
  useImperativeHandle,
} from 'react'
import { Row, Col, notification, Spin } from 'antd'
import moment from 'moment'
import { FCTable, FCPagination, FCForm, ControlType } from '../../index'
import './FCQueryPage.less'

const DATE_FORMAT = 'YYYY-MM-DD'

function FCQueryPage(props) {
  const {
    pageRef,
    tableProps,
    searchFormProps,
    paginationProps,
    apiConfigs,
    detailPage, // TODO
    onBeforeQuery = () => {},
    onBeforeQuerys = () => {}, // 不包含分页查询
    isBlock = () => {
      //默认不阻止页面查询，通过返回false阻止页面查询
      return true
    },
    ...restProps
  } = props

  const {
    fields,
    layoutProps,
    initialValues,
    extraTopRight,
    extraTail,
    ifDateConvertToString = true,
    isButtonLineFeed, //按钮是否换行
    ...restFormProps
  } = searchFormProps
  const {
    name,
    title,
    columns,
    rowKey,
    rowSelectionType = 'none',
    onRowClick,
    onRowDoubleClick,
    extraTopRight: tableExtraTopRight,
    actionColumn,
    selectedRowKeys,
    tableEvents = {},
  } = tableProps

  const onSelectionChange = (record, selected, selectedRows, nativeEvent) => {
    const { onSelectionChange } = tableEvents
    if (onSelectionChange) {
      onSelectionChange(record, selected, selectedRows, nativeEvent)
    }
  }
  const onSelectionAllChange = (selected, selectedRows, changeRows) => {
    const { onSelectionAllChange } = tableEvents
    if (onSelectionAllChange) {
      onSelectionAllChange(selected, selectedRows, changeRows)
    }
  }

  const fixedTableProps = {
    title,
    columns,
    rowKey,
    rowSelectionType,
    selectedRowKeys,
    onSelectionChange,
    onSelectionAllChange,
    onRowClick,
    onRowDoubleClick,
    extraTopRight: tableExtraTopRight,
    actionColumn,
    // scroll: { x: '100vw', y: 500 },
    pagination: false,
  }
  const defaultPaginationProps = paginationProps
    ? { ...paginationProps }
    : {
        pageSize: 20,
        showSizeChanger: true,
      }
  const { query } = apiConfigs

  // ref
  const paramFormRef = useRef(`queryParamForm`)

  // State
  const [params, setParams] = useState({})
  const [dataList, setDataList] = useState([])
  const [pagiProps, setPagiProps] = useState({
    ...defaultPaginationProps,
    current: 1,
    totalCount: 0,
  })
  const [loading, setLoading] = useState(false)

  // Memo
  const datas = useMemo(() => {
    const list = dataList?.filter((item) => item[rowKey] !== null)
    return list
  }, [dataList])

  // method
  const doQuery = (fromValue = {}) => {
    onBeforeQuery(fromValue)
    // 查询前调用，分页不调用
    if (!pagiProps.pageIndex) {
      onBeforeQuerys(fromValue)
    }
    const { pageIndex = 1, pageSize } = pagiProps
    const data = {  queryDto: { ...fromValue, ...params }}
    data.currentPage = pageIndex
    data.pageSize = pageSize

    // 添加一个外部页面可以阻止页面查询的方法
    if (isBlock()) {
      setLoading(true)

      query({
        params: data,
        success: (res) => {
          const { pageList, currentPage, pageSize, totalCount } = res
          const newPagiProps = { ...pagiProps, current: currentPage, totalCount }
          setDataList(pageList)
          setPagiProps(newPagiProps)
          setLoading(false)
        },
        failure: (res) => {
          setLoading(false)
        },
      })
    }
  }

  const reDoQuery = async (pagination) => {
    try {
      await paramFormRef.current.validateFields()
      // 成功
      if (pagination?.pageIndex || pagination?.pageSize) {
        setPagiProps({ ...pagiProps, ...pagination })
      } else {
        doQuery()
      }
    } catch (errorInfo) {
      // console.log('Failed:', errorInfo)
    }
  }

  useEffect(() => {
    if (pagiProps.pageIndex) {
      doQuery()
    }
  }, [pagiProps.pageIndex, pagiProps.pageSize])

  // 暴露给外部组件的方法
  useImperativeHandle(pageRef, () => ({
    getDatas: () => dataList,
    reQuery: (pagination) => {
      reDoQuery(pagination)
    },
    getParams: () => paramFormRef.current.getFieldsValue(),
    getForm: () => paramFormRef.current,
  }))

  // Table event
  const onPageChange = (pageIndex, pageSize) => {
    const newPagiProps = { ...pagiProps, pageIndex, pageSize }
    setPagiProps(newPagiProps)
  }

  const onChangeNumChange = useCallback(
    (pageIndex, pageSize) => {
      onPageChange(pageIndex, pageSize)
    },
    [pagiProps]
  )

  const onShowSizeChange = useCallback(
    (pageIndex, pageSize) => {
      onPageChange(pageIndex, pageSize)
    },
    [pagiProps]
  )

  // paramForm event
  const doSubmit = (values) => {
    const rValues = { ...values }
    // debugger
    if (ifDateConvertToString) {
      fields?.forEach((field) => {
        if (field.controlType === ControlType.DATE_PICKER && rValues[field.name]) {
          rValues[field.name] = moment(rValues[field.name]).format(DATE_FORMAT)
        }
      })
    }
    // debugger
    setParams(rValues)
    doQuery(rValues)
  }

  const onFormFinish = useCallback((values) => {
    // setPagiProps({ ...pagiProps, pageIndex: 1 })
    doSubmit(values)
  }, [])

  const onFormFinishFailed = useCallback((values, errorFields, outOfDate) => {
    // console.log(values)
  }, [])

  const onValuesChange = useCallback((changedValues, allValues) => {
    // console.log(changedValues)
  }, [])

  return (
    <div className="fc-querypage-container">
      <div className="query-panel">
        <FCForm
          name="queryForm"
          formRef={paramFormRef}
          initialValues={initialValues}
          fields={fields}
          layoutProps={layoutProps}
          onFinish={onFormFinish}
          onFinishFailed={onFormFinishFailed}
          onValuesChange={onValuesChange}
          extraTopRight={extraTopRight}
          extraTail={extraTail}
          isButtonLineFeed={isButtonLineFeed}
          {...restFormProps}
        />
      </div>
      <div className="query-result-panel">
        <div className="table-spin-container" style={{ display: loading ? '' : 'none' }}>
          <Spin size="large" spinning={loading} />
        </div>
        <FCTable {...fixedTableProps} dataSource={datas} />
        <Row style={{ margin: '16px 0' }}>
          <Col flex="auto" />
          <Col flex="none">
            <div style={{ padding: '0 16px' }}>
              <FCPagination
                {...pagiProps}
                onChange={onChangeNumChange}
                onShowSizeChange={onShowSizeChange}
              />
            </div>
          </Col>
        </Row>
      </div>
    </div>
  )
}

export default FCQueryPage
